<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="150px">
      <el-form-item label="机构单位" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入机构单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库年份" prop="storYear">
        <el-input
          v-model="queryParams.storYear"
          placeholder="请输入入库年份"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位有无问题" prop="isUnit">
        <el-select v-model="queryParams.isUnit" placeholder="请选择单位有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商有无问题" prop="isSupplier">
        <el-select v-model="queryParams.isSupplier" placeholder="请选择供应商有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据整体有无问题" prop="noWrong">
        <el-select v-model="queryParams.noWrong" placeholder="请选择导入有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['work:money:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['work:money:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['work:money:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button 
          type="info" 
          plain 
          icon="el-icon-upload2" 
          size="mini" 
          @click="handleImport" 
          v-hasPermi="['work:money:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['work:money:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="moneyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" width="55" align="center" prop="ids" />
      <el-table-column label="入库单位" align="center" prop="unitName" />
      <el-table-column label="入库供应商" align="center" prop="supplierName" />
      <el-table-column label="入库年份" width="80" align="center" prop="storYear" />
      <el-table-column label="01月" width="80" align="center" prop="storMoney01" />
      <el-table-column label="02月" width="80" align="center" prop="storMoney02" />
      <el-table-column label="03月" width="80" align="center" prop="storMoney03" />
      <el-table-column label="04月" width="80" align="center" prop="storMoney04" />
      <el-table-column label="05月" width="80" align="center" prop="storMoney05" />
      <el-table-column label="06月" width="80" align="center" prop="storMoney06" />
      <el-table-column label="07月" width="80" align="center" prop="storMoney07" />
      <el-table-column label="08月" width="80" align="center" prop="storMoney08" />
      <el-table-column label="09月" width="80" align="center" prop="storMoney09" />
      <el-table-column label="10月" width="80" align="center" prop="storMoney10" />
      <el-table-column label="11月" width="80" align="center" prop="storMoney11" />
      <el-table-column label="12月" width="80" align="center" prop="storMoney12" />
      <el-table-column label="数据有无问题" width="80" align="center" prop="noWrong" >
        <template slot-scope="scope">
          <span>{{ scope.row.noWrong === '0' ? '有问题' : (scope.row.noWrong === '1' ? '没问题' : scope.row.noWrong) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['work:money:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['work:money:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库金额对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <div v-if="form.noWrong==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前页面整体都没有问题，可以正常使用！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前页面存在不标准数据类型，请尽快修改！
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单位" prop="unitId">
              <el-select v-model="form.unitId" placeholder="请选择入库单位" filterable @change="handleUnitChange">
                <el-option
                  v-for="unit in unitOptions"
                  :key="Number(unit.ids)"
                  :label="unit.unitName"
                  :value="Number(unit.ids)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入单位" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入入库单位名称" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isUnit==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前入库单位与导入单位一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前入库单位与导入单位不一致！
            </div> 
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择入库供应商" filterable @change="handleSupplierChange" >
                <el-option
                  v-for="supplier in supplierOptions"
                  :key="Number(supplier.ids)"
                  :label="supplier.supplierName"
                  :value="Number(supplier.ids)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入供应商" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入导入供应商名称" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isSupplier==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前备注与字典备注一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前备注与字典备注不一致！
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入库年份" prop="storYear">
              <el-input-number v-model="form.storYear" placeholder="请输入入库年份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="01月入库金额" prop="storMoney01">
              <el-input-number v-model="form.storMoney01" placeholder="请输入01月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="02月入库金额" prop="storMoney02">
              <el-input-number v-model="form.storMoney02" placeholder="请输入02月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="03月入库金额" prop="storMoney03">
              <el-input-number v-model="form.storMoney03" placeholder="请输入03月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="04月入库金额" prop="storMoney04">
              <el-input-number v-model="form.storMoney04" placeholder="请输入04月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="05月入库金额" prop="storMoney05">
              <el-input-number v-model="form.storMoney05" placeholder="请输入05月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="06月入库金额" prop="storMoney06">
              <el-input-number v-model="form.storMoney06" placeholder="请输入06月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="07月入库金额" prop="storMoney07">
              <el-input-number v-model="form.storMoney07" placeholder="请输入07月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="08月入库金额" prop="storMoney08">
              <el-input-number v-model="form.storMoney08" placeholder="请输入08月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="09月入库金额" prop="storMoney09">
              <el-input-number v-model="form.storMoney09" placeholder="请输入09月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="10月入库金额" prop="storMoney10">
              <el-input-number v-model="form.storMoney10" placeholder="请输入10月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="11月入库金额" prop="storMoney11">
              <el-input-number v-model="form.storMoney11" placeholder="请输入11月入库金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="12月入库金额" prop="storMoney12">
              <el-input-number v-model="form.storMoney12" placeholder="请输入12月入库金额" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.titleImport" :visible.sync="upload.openImport" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.openImport = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMoney, getMoney, delMoney, addMoney, updateMoney } from "@/api/work/money"
import { findAllUnitList } from "@/api/work/unit"
import { findAllSupplierList } from "@/api/work/supplier"
import { getToken } from "@/utils/auth";

export default {
  name: "Money",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库金额表格数据
      moneyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 机构单位选项
      unitOptions: [],
      // 供应商选项
      supplierOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitName: null,
        isUnit: null,
        supplierName: null,
        isSupplier: null,
        storYear: null,
        noWrong: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        unitId: [
          { required: true, message: "入库单位不能为空", trigger: "blur" }
        ],
        unitName: [
          { required: true, message: "导入单位不能为空", trigger: "blur" }
        ],
        isUnit: [
          { required: true, message: "导入单位是否正确不能为空", trigger: "change" }
        ],
        supplierId: [
          { required: true, message: "入库供应商不能为空", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "导入供应商不能为空", trigger: "blur" }
        ],
        isSupplier: [
          { required: true, message: "导入供应商是否正确不能为空", trigger: "change" }
        ],
        storYear: [
          { required: true, message: "入库年份不能为空", trigger: "change" },
          { validator: (rule, value, callback) => {
            if (value && (!/^\d{4}$/.test(value) || value < 1900 || value > 2200)) {
              callback(new Error('请输入4位有效年份数字(1900-2200)'));
            } else {
              callback();
            }
          }, trigger: 'change' }
        ],
        noWrong: [
          { required: true, message: "导入整体是否有错不能为空", trigger: "blur" }
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入弹窗）
        openImport: false,
        // 弹出层标题（自己填写）
        titleImport: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 上传的地址,即后端接口地址
        url: process.env.VUE_APP_BASE_API + "/work/money/importData"
      },
    }
  },
  created() {
    this.getList()
    this.getUnitOptions()
    this.getSupplierOptions()
  },
  methods: {
    /** 获取机构单位选项 */
    getUnitOptions() {
      findAllUnitList().then(response => {
        this.unitOptions = response.data || []
      })
    },
    /** 机构单位选择变更处理 */
    handleUnitChange(value) {
      // 根据选中的unitId查找对应的unitName
      const selectedUnit = this.unitOptions.find(item => item.ids === value);
      if (selectedUnit) {
        this.form.unitName = selectedUnit.unitName;
        this.form.isUnit = '1';
      } else {
        this.form.unitName = '';
        this.form.isUnit = '0';
      }
      this.isWrong();
    },
    /** 获取供应商选项 */
    getSupplierOptions() {
      findAllSupplierList().then(response => {
        this.supplierOptions = response.data || []
      })
    },
    /** 供应商选择变更处理 */
    handleSupplierChange(value) {
      // 根据选中的supplierId查找对应的supplierName
      const selectedSupplier = this.supplierOptions.find(item => item.ids === value);
      if (selectedSupplier) {
        this.form.supplierName = selectedSupplier.supplierName;
        this.form.isSupplier = '1';
      } else {
        this.form.supplierName = '';
        this.form.isSupplier = '0';
      }
      this.isWrong();
    },
    /** 机构单位和供应商变更后调用该方法，判断是否一致了 */
    isWrong() {
      if(this.form.isUnit==='1' && this.form.isSupplier==='1'){
        this.form.noWrong = '1';
      }else{
        this.form.noWrong = '0';
      }
    },
    /** 查询入库金额列表 */
    getList() {
      this.loading = true
      listMoney(this.queryParams).then(response => {
        this.moneyList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        ids: null,
        unitId: null,
        unitName: null,
        isUnit: null,
        supplierId: null,
        supplierName: null,
        isSupplier: null,
        storYear: null,
        storMoney01: null,
        storMoney02: null,
        storMoney03: null,
        storMoney04: null,
        storMoney05: null,
        storMoney06: null,
        storMoney07: null,
        storMoney08: null,
        storMoney09: null,
        storMoney10: null,
        storMoney11: null,
        storMoney12: null,
        noWrong: null,
        addTime: null,
        upTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ids)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加入库金额"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const ids = row.ids || this.ids
      getMoney(ids).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改入库金额"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ids != null) {
            updateMoney(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addMoney(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const idss = row.ids || this.ids
      this.$modal.confirm('是否确认删除入库金额编号为"' + idss + '"的数据项？').then(function() {
        return delMoney(idss)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('work/money/export', {
        ...this.queryParams
      }, `storMoney_${new Date().getTime()}.xlsx`)
    },
    /**导入excel表*/
    handleImport() {
      this.upload.titleImport = "导入入库金额表";
      this.upload.openImport = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('work/money/importTemplate', {
        ...this.queryParams
      }, `入库金额模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true
      });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
}
</script>
